// pages/search/search.js
const app =getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hotList:[],
    delay:null,
    kw:"",
    searHistory:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '正在加载···',
    })
    wx.request({
      url: 'https://apis.netstart.cn/vmovier/search',
      success:res=>{
        wx.hideLoading();
        let data = res.data.data
        let {recommend_keywords}= data;
        this.setData({
          hotList:recommend_keywords
        })
      },
      fail:err=>{
        console.log(err);
      }
    })
    // 获取用户的搜索历史
    if(app.globalData.searHistory){
      this.setData({
        searHistory:app.globalData.searHistory
      })
    }
  },
  onHide(){
    this.setData({
      kw:""
    })
  },

  toSearchList(){
    wx.navigateTo({
      url: '../searchList/searchList?kw='+this.data.kw,
    })
  },

  // 获取输入框输入的值
  getInput(e){
    if (this.data.delay) {
      clearTimeout(this.data.delay);
    }
    this.data.delay = setTimeout(()=>{
      let value = e.detail.value;
      this.setData({
        kw:value
      })
    },500)
  },
  
  // 获取用户点击的关键词
  getKeyWord(e){
    let kw= e.currentTarget.dataset.kw;
    this.setData({
      kw:kw
    })
    this.toSearchList()
  },

  // 搜索用户输入的词语，添加到历史记录中
  toSearch(){
    console.log("kw",this.data.kw);
    let list=this.data.searHistory;
    list.push(this.data.kw)
    this.setData({
      searHistory:list
    })
    app.globalData.searHistory=this.data.searHistory;
    this.toSearchList();
  },

  // 清除历史记录
  clearHistory(){
    app.globalData.searHistory=null;
    this.setData({
      searHistory:[]
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})